package be.groept.ace.enquete.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import be.groept.ace.enquete.model.beans.User;
import be.groept.ace.enquete.model.dao.DAOCommand;
import be.groept.ace.enquete.model.dao.DAOFactory;
import be.groept.ace.enquete.model.dao.DAOManager;
import be.groept.ace.enquete.model.exceptions.DAOException;
import be.groept.ace.enquete.utils.ServletUtils;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static Logger logger = Logger.getLogger(LoginServlet.class);
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("user");
		if(user == null) {
			request.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(request, response);
		} else {
			response.sendRedirect("/");
		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		final String email = request.getParameter("email");
		final String password = request.getParameter("password");
		boolean authenticated = false;
		
		if ( !ServletUtils.isNullOrEmpty(email) && !ServletUtils.isNullOrEmpty(password)) {
			logger.debug(String.format("Check user credentials: email: %s | password: %s", email, password ));
			DAOManager daoManager = null;
			try {
				daoManager  = (new DAOFactory()).createDAOManager(DAOFactory.PERSISTENCEMODE.MYSQL);
			} catch (DAOException daoe) {
				logger.fatal(daoe.toString());
				throw new ServletException(daoe.getMessage() + "\nPlease configure the resource in the META_INF/context.xml file");
			}
			try {
				User user = (User) daoManager.transactionAndClose(new DAOCommand() {
	
					@Override
					public Object execute(DAOManager daoManager) throws DAOException {
						return daoManager.getUserDAO().findUser(email.toLowerCase(), password);
					}
					
				});
				
				if(user != null) {
					session.setAttribute("user", user);
					authenticated = true;
					logger.info(String.format("User %s correctly logged in.", user));
				} else {
					logger.error(String.format("Invalid login for user with email: %s.", email));
				}
			} catch (DAOException daoe) {
				logger.fatal(daoe.toString());
				throw new ServletException(daoe.getMessage());
			}
			
		} 

		
		if(!authenticated) {
			//TODO error message
			logger.debug("Forward to login page...");
			request.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(request, response);
		} else {
			String url = (String) session.getAttribute("requestedUrl");
			if(url == null) {
				url = "/";
			}
			logger.debug(String.format("Redirect to %s...", url));
			response.sendRedirect(response.encodeRedirectURL(url));
		}
	}
}
